In [1]:
for i in range(3):
a = i * 7 #0, 7, 14
b = i + 2 #2, 3, 4
c = a * b # 0, 21, 56
#만약 이 range값이 3017, 5033일 경우에는 무슨 값인지 알 수 없다. 이 때 쉽게 a,b,c값이 무엇인지 찾는 방법을 소개
디버깅? de+bugg+ing => 버그를 잡는다
Jupyter는 Python interpreter이다. 이것을 웹 환경에서 쓸 수 있도록 바꾼 것이 Jupyter Notebook 이다.
In [2]:
name = "KiPyo Kim"
age = 29
from IPython import embed
embed()
In [4]:
for i in range(3):
a = i * 7
b = i + 2
c = a * b
embed()
In [5]:
from IPython import embed; embed() #보통 디버깅 할 때 이렇게 해서 단축키로 지정하고 많이 쓴다.
In [ ]:
for i in range(100):
from IPython import embed; embed()
#이렇게 하면 무한루프에 빠진다. 커널을 종료하는 수밖에...
In [8]:
def fibo(n):
if n <= 0:
return 0
if n == 1:
return 1
embed()
return fibo(n-1) + fibo(n-2)
In [16]:
fibo(5)
Out[16]:
In [1]:
class Student():
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
from IPython import embed; embed()
return (self.name, self.age)
In [2]:
kkp = Student("kipoy", 29)
In [3]:
kkp.introduce()
Out[3]:
In [4]:
def fibo(n):
if n <= 0:
return 0
if n == 1:
return 1
print("fibo({n}) = fibo({n_1}) + fibo({n-2})".format(n=n, n_1=n-1, n_2=n-2))
return fibo(n-1) + fibo(n-2)
In [5]:
fibo(3)
In [6]:
fibo(10)
In [7]:
import logging
In [8]:
# logging -> debug, info, warning, danger, critical...
logging.warning("hello world")
In [9]:
name #뒤에 따라 오는 주석들 Traceback 이 있다.
In [10]:
if True
print("hello world")
In [11]:
ab
In [12]:
def error(a, b):
a = b + 1
print(a)
error
Out[12]:
In [13]:
2 + "김기표"
In [14]:
{}["somtthing"]
In [15]:
{}.append()
In [16]:
with open("./not_exist_file", "r") as f:
pass
Exception Handling
우리가 직접 예외를 만드는 방법(FibonacciShouldGetPositiveNumberError => 우리만의 예외)
In [17]:
NameError
Out[17]:
In [18]:
Exception?
In [19]:
def append_string_to_hello(string):
return "hello, " + string
In [20]:
append_string_to_hello("world")
Out[20]:
In [21]:
append_string_to_hello(13)
In [22]:
"hello, " + 3
#str + int, implicit(함축적)한 방법이다.
#Python은 형변환이 되지 않기 때문이다.(형변환 잘 되는 것은 루비)
#자유도가 높거나 해서 좋은 언어는 아니다. 언어 특성에 맞게 사용하면 된다.
In [23]:
"hello" + str(3)
# str + str(int), explicit(명시적)한 방법이다.
Out[23]:
In [24]:
awesome_list = ["world", "hello", "python", 5678, "fastcampus"]
for awesome in awesome_list:
# 예외 처리가 가능한 장소 [1] => 밑에 있는 케이스에서만 예외처리가 가능
print(append_string_to_hello(awesome))
In [25]:
def append_string_to_hello(string):
# 예외처리가 가능한 장소(2) => 함수 불렀을 모든 경우에서 예외 처리 가능
# 그래서 2번에서 해보겠다.
return "hello, " + string
In [28]:
def append_string_to_hello(string):
# 예외처리가 가능한 장소
# 예외처리 => try:-except: (항상 이런 방법으로 한다.)
try:
return "hello, " + string
except TypeError as err:
print("오류" * 40)
In [29]:
append_string_to_hello(123)
In [30]:
def append_string_to_hello(string):
try:
return "hello, " + string
except TypeError as err:
#TypeError는 class다. 즉 에러 하나하나 자체는 클래스로 만들어진 에러 객체이다.
print(err)
In [31]:
append_string_to_hello(123)
In [32]:
def append_string_to_hello(string):
try:
return "hello, " + string
except TypeError as err:
return err
In [33]:
append_string_to_hello(123)
Out[33]:
In [34]:
def append_string_to_hello(string):
try:
return "hello, " + string
except: #이렇게 할 경우 모든 에러에 대해 예외처리. 일반적으로 많이 사용
return err
In [35]:
append_string_to_hello(123)
In [36]:
def append_string_to_hello(string):
try:
return "hello, " + string
except {TypeError, AttributeError} as err: #이렇게도 쓰나 잘 쓰진 않는다.
return err
In [37]:
append_string_to_hello(123)
In [38]:
def append_string_to_hello(string):
try:
return "hello, " + string
except TypeError as err:
#알람을 받을 수 있도록 넣을수도 있다.
print("send_sms")
raise
In [39]:
append_string_to_hello(123)
In [40]:
def append_string_to_hello(string):
try:
return "hello, " + string
except TypeError as err:
print("send_sms")
raise
except AttributeError as err:
pass
In [41]:
append_string_to_hello(123)
In [42]:
def append_string_to_hello(string):
try:
return "hello, " + string
except TypeError as err:
print("send_sms")
print(err)
# raise
except AttributeError as err:
pass
finally: #예외가 발생했던 아니던 어쨌든 실행하고 싶을 때
print("어쨌던 끝남")
In [43]:
append_string_to_hello(123)
In [44]:
awesome_list = ["world", "hello", "python", 5678, "fastcampus"]
for awesome in awesome_list:
print(append_string_to_hello(awesome))
In [45]:
def fibo(x):
if x < 0:
# err = FibonacciShouldNotHaveNegativeNumberError()
# raise err
#일반적으로 위와 같은 2줄이 아닌 아래와 같은 1줄로 적는다.
raise FibonacciShouldNotHaveNegativeNumberError()
if x == 0:
return 0
if x == 1:
return 1
return fibo(x-1) + fibo(x-2)
In [46]:
#Exception Class
class FibonacciShouldNotHaveNegativeNumberError(Exception):
def __init__(self):
pass
In [47]:
fibo(-1)
In [48]:
raise FibonacciShouldNotHaveNegativeNumberError()
# 다른 에러들은 수정 요구 사항까지 나온다.
In [49]:
"hello, " + 5678
# 노란색 에러는 수정 요구 사항
# 이건 어디서 수정 가능하냐? def __str__(self): 여기서!
In [50]:
class FibonacciShouldNotHaveNegativeNumberError(Exception):
def __init__(self):
pass
def __str__(self):
return "피보나치 수열은 index 값으로 양수를 받아야 합니다"
In [51]:
raise FibonacciShouldNotHaveNegativeNumberError()
In [52]:
def fibo(x):
if x < 0:
raise FibonacciShouldNotHaveNegativeNumberError(x)
if x == 0:
return 0
if x == 1:
return 1
return fibo(x-1) + fibo(x-2)
In [53]:
class FibonacciShouldNotHaveNegativeNumberError(Exception):
def __init__(self, n):
self.n = n
def __str__(self):
return "이 함수는 index 값으로 양수를 받아야 합니다. (입력받은 값: {n})".format(n=self.n) #에러메세지 요구사항
In [54]:
fibo(-13)
In [55]:
def Factorial(n):
if n == 1:
return 1
return n * Factorial(n-1)
In [56]:
Factorial(5)
Out[56]:
In [57]:
def Factorial(n):
if n < 0:
raise FactorialShouldGetPositiveIndexError(n)
if n == 1:
return 1
return n * Factorial(n-1)
In [58]:
class FactorialShouldGetPositiveIndexError(Exception):
def __init__(self, n):
self.n = n
def __str__(self):
return "factorial function should get positive index. (input: {n})".format(n=self.n)
In [59]:
Factorial(-3)
<우분투 개념>
<우분투 관련 명령어>
<우분투에서 pyenv 설치>